import { useBoolean } from '@/hooks/useBoolean.js'
import Service from '@/utils/service.js'
import { setTableScroll } from '@/utils/common.js'

export function useTableList(url, options = {}) {
  const _options = {
    rowKey: 'id',
    callback: null,
    useRadioSelect: false,
    autoHeight: true,
    tableSelector: '.ant-table-wrapper',
  }
  const { rowKey, callback, useRadioSelect, autoHeight, tableSelector } = { ..._options, ...options }

  const [loading, toggleLoading] = useBoolean()
  const dataSource = ref([])
  const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 0,
    // pageSizeOptions: ['10', '20', '30'],
    // showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total, range) => `第 ${range[0]}-${range[1]} 项 （共 ${total} 项）`,
  })

  const selectedRowKeys = ref([])
  const selectedRowKey = ref(null)
  const selectedRows = ref([])
  const selectedRow = ref({})

  const setSelectItem = item => {
    selectedRowKeys.value = [item[rowKey]]
    selectedRowKey.value = item[rowKey]
    selectedRows.value = [item]
    selectedRow.value = item
  }

  const getList = async (params = {}) => {
    try {
      toggleLoading(true)
      const { code, data } = await Service.getAction(url, {
        ...params,
        current: pagination.value.current,
        pageSize: pagination.value.pageSize,
      })
      if (code === 200) {
        dataSource.value = data.records
        pagination.value.total = data.total
        if (useRadioSelect && dataSource.value.length) {
          const firstItem = dataSource.value[0]
          setSelectItem(firstItem)
        }
      }
    } finally {
      callback && callback()
      toggleLoading(false)
    }
  }

  const tableChange = (pag, filters, sorter) => {
    pagination.value.current = pag.current
    pagination.value.pageSize = pag.pageSize
  }

  watch(
    () => [pagination.value.current, pagination.value.pageSize],
    () => {
      getList()
    }
  )

  const onSelectChange = (_, _selectedRows) => {
    const item = toRaw(_selectedRows[0])
    setSelectItem(item)
  }

  const rowSelection = {
    type: 'radio',
    selectedRowKeys,
    onChange: onSelectChange,
  }

  const customRow = record => {
    const selected = record[rowKey] === selectedRowKey.value
    return {
      style: {
        cursor: selected ? 'default' : 'pointer',
      },
      onclick: () => {
        const item = toRaw(record)
        setSelectItem(item)
      },
    }
  }

  const tableScrollY = ref('')
  onMounted(() => {
    if (autoHeight) {
      tableScrollY.value = setTableScroll(tableSelector)
    }
  })

  return {
    loading,
    dataSource,
    pagination,
    selectedRow,
    rowSelection,
    tableScrollY,
    getList,
    tableChange,
    onSelectChange,
    customRow,
  }
}
